var assert = require('../assert');
exports.index = function (req, res, next) {
    var shopId = req.params.shopId;
    var userId = assert.getUserId(req);
    var isVisited = req.cookies.isVisited;
    var url = '/kdShop/' + shopId;
    if (userId) {
        url = url + '?userId=' + userId;
    }
    if(!isVisited){
        if(userId){
            url += '&unvisited=1'
        }else{
            url += '?unvisited=1'
        }
    }
    var JADE_VAR = assert.getJADEVAR();
    if (shopId) {
        assert.apiParseRequest('get', url, {}).then(function (results) {
            if(results){
                var shopInfo = results.shopInfo;
                var shopProducts = results.shopProducts;
                var mainPage = shopProducts.mainPage;
                delete shopProducts.mainPage;
                JADE_VAR.shopInfo = shopInfo;
                JADE_VAR.mainPage = mainPage;
                JADE_VAR.productsCount = Object.keys(shopProducts).length;
                JADE_VAR.Products = shopProducts;
                res.cookie('isVisited','1',{path:'/'});
                var nav = [];
                for (var key in shopProducts) {
                    nav.push(key);
                }
                JADE_VAR.nav = nav;
                res.render('index', JADE_VAR)
            }else{
                res.render('error', assert.getRes(404, "服务失败", {storeGet:true}, true));
            }

        }, function (err, error) {
            res.render('error', assert.getRes(404, err, {}, true));
        });
    } else {
        res.render('error', assert.getRes(404, "页面不存在", {}, true));
    }
};
